﻿using DevExpress.LookAndFeel;
using DevExpress.Skins;
using DevExpress.XtraBars.Helpers;
using HNRoadFormatConverter.Commons;
using HNRoadFormatConverter.MyConfig;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using HNRoadFormatConverter.MyContrls;
using System.IO;
using HNRoadFormatConverter.MyEntitys;
using System.Runtime.InteropServices;
using DevExpress.XtraTreeList.Nodes;
using HNRoadFormatConverter.Entitys;
using System.Web.Security;
using System.Threading.Tasks;
using System.Diagnostics;
using DevExpress.XtraBars;
using System.Text.RegularExpressions;
using DevExpress.Utils.About;
using System.Windows.Input;
using DevExpress.XtraRichEdit.Import.Rtf;
using DevExpress.Utils.Internal;
using DevExpress.XtraPrinting;
using System.Data.Linq.Mapping;
using System.Globalization;
using NPOI.SS.Formula.Functions;
using static DevExpress.Utils.Drawing.Helpers.NativeMethods;
using DevExpress.Utils.DPI;
using DevExpress.Data.Helpers;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using DevExpress.XtraLayout.Customization;
using DevExpress.XtraEditors;
using Org.BouncyCastle.Math.EC;
using NPOI.Util;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using DevExpress.XtraEditors.Controls.Rtf;
using DevExpress.XtraEditors.Repository;
using HNRoadFormatConverter.Properties;
using Microsoft.WindowsAPICodePack.Dialogs;
using NPOI.OpenXmlFormats.Dml;
using DevExpress.Office.Utils;

namespace HNRoadFormatConverter
{
    public partial class Form1 : DevExpress.XtraBars.Ribbon.RibbonForm
    {
        public string _Suf = ".jpg"; // 文件名后缀
        private static Config _config = ConfigManager.GetConfig();
        private static LogHelper _log = new LogHelper(typeof(Form1));
        [DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
        private static extern int StrCmpLogicalW(string psz1, string psz2);
        private string Chktxt_Path { get; set; }
        public Form1()
        {
            InitializeComponent();
            AddUI();
            SetDefaultUI();
            // HandelMap();
            _Projects = new List<ProjectInfo>();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

            barButtonItem15.Caption = "交通部数据";
            //  barLoad.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
            barButtonItem3.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
            barLoad.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
            barEditItem1.EditValue = _config.NowModel;
            barEditItem1.EditValueChanged += BarEditItem1_EditValueChanged;

            // 创建 RepositoryItemComboBox 并设置为 BarEditItem 的编辑控件
            RepositoryItemComboBox repositoryItemComboBox = barEditItem1.Edit as RepositoryItemComboBox;
            repositoryItemComboBox.Items.Clear();
            // 向 RepositoryItemComboBox 添加子项
           repositoryItemComboBox.Items.Add("交通部2024规范");
           repositoryItemComboBox.Items.Add("河南省单位一农村路定制");
           repositoryItemComboBox.Items.Add("湖南省单位一定制");
           repositoryItemComboBox.Items.Add("重庆市单位一定制");
           repositoryItemComboBox.Items.Add("甘肃省单位一定制");
           repositoryItemComboBox.Items.Add("河北省单位一定制");
           repositoryItemComboBox.Items.Add("河北省单位二定制");
           repositoryItemComboBox.Items.Add("江苏省单位一定制");
           repositoryItemComboBox.Items.Add("安徽省单位一定制");
        }
        private void HandelMap()
        {
            string str_uil = AppDomain.CurrentDomain.BaseDirectory + "Map\\BaiduMap.html";
            Uri uri = new Uri(str_uil);
            //myWebBrowser1.webBrowser1.Url = uri;
            // myWebBrowser1.webBrowser1.ObjectForScripting = true;
        }
        private void AddUI()
        {
            var skinCon = new DevExpress.XtraBars.SkinRibbonGalleryBarItem();
            ribbonPageGroup5.ItemLinks.Add(skinCon);
            SkinHelper.InitSkinGallery(skinCon);
        }
        private void SetDefaultUI()
        {
            this.defaultLookAndFeel1.LookAndFeel.SkinName = _config.DefaultSkin;

            
        }
        private List<ProjectInfo> _Projects;
        private void barLoad_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //var str =   File.ReadAllText(@"E:\工作\工作数据\等级公路2018数据\新建文件夹\__上行_测试_d湖北省_武汉市_江夏区_20211117_171148\ConverSource\LSEC989989A\识别结果\\LSEC989989A-沥青路面损坏-0.599-1.001.csv");
            this.treeList2.Nodes.Clear();
            List<DirectoryInfo> projects = new List<DirectoryInfo>();
            CommonOpenFileDialog dlg = new CommonOpenFileDialog()
            {
                IsFolderPicker = true, //设置为true为选择文件夹，设置为false为选择文件
                Title = "选择文件夹",
                InitialDirectory = _config.UserPath,
            };

            if (dlg.ShowDialog() != CommonFileDialogResult.Ok)
            {
                return;
            }



            if (dlg.FileName != String.Empty)
            {
                string selectPath = dlg.FileName;
                if (selectPath.Substring(dlg.FileName.Length - 1) == "\\")
                {
                    selectPath = selectPath.Remove(dlg.FileName.Length - 1);
                }
                this.Chktxt_Path = selectPath;
                _config.UserPath = selectPath;
                ConfigManager.SaveConfig();
                projects = GetAllProjectPath(selectPath);
                foreach (DirectoryInfo dir in projects)
                {
                    ProjectInfo proj = new ProjectInfo(dir.FullName);
                    proj._DataDir = dir;
                    _Projects.Add(proj);
                }
                _Projects.Sort((a, b) => StrCmpLogicalW(a._DataDir.Name, b._DataDir.Name));
                foreach (var pro in _Projects)
                {
                    TreeListNode node = this.treeList2.AppendNode(null, null);
                    // node.SetValue("name",pro._DataDir.Name) ;
                    node.SetValue("data", pro._DataDir.Name);
                }
            }

        }
        /// <summary>
        /// 获取所有文件
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private List<DirectoryInfo> GetAllProjectPath(string path)
        {
            List<DirectoryInfo> projects = new List<DirectoryInfo>();
            _Projects.Clear();
            if (Directory.Exists(path))
            {
                DirectoryInfo dir = null;
                DirectoryInfo[] sdirs = null;
                try
                {
                    dir = new DirectoryInfo(path);
                    sdirs = dir.GetDirectories();
                }
                catch (System.Exception)
                {

                    dir = null;
                    sdirs = null;
                }
                if (sdirs != null)
                {
                    foreach (DirectoryInfo d in sdirs)
                    {
                        if (File.Exists(d.FullName + "\\ProjectInfo.txt"))
                        {
                            projects.Add(d);

                        }

                        else
                        {
                            projects.AddRange(GetAllProjectPath(d.FullName).ToArray());
                        }
                    }
                }
            }
            if (File.Exists(path + "\\ProjectInfo.txt"))
            {
                projects.Add(new DirectoryInfo(path));
            }
            return projects;
        }


        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            _config.DefaultSkin = this.defaultLookAndFeel1.LookAndFeel.SkinName;
            ConfigManager.SaveConfig();
        }

        private void ribbonStatusBar1_Click(object sender, EventArgs e)
        {

        }

        private void barButtonItem2_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {


        }

        private void btn_check_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {

        }


        private CityModelItem currentStandard = CityModelItem.交通部2024规范;
        private async void barButtonItem1_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
      

            handelCsvFiles.Clear();
            string targetBasePath = "";
            if (_Projects.Count <= 0)
            {
                MessageBox.Show("您还没有导入任何合格工程");
                return;
            }

            CommonOpenFileDialog dlg = new CommonOpenFileDialog()
            {
                IsFolderPicker = true, //设置为true为选择文件夹，设置为false为选择文件
                Title = "请选择放置地点",
               
            };

            if (dlg.ShowDialog() != CommonFileDialogResult.Ok)
            {
                return;
            }
            if (string.IsNullOrEmpty(dlg.FileName))
            {

                return;
            }
            targetBasePath = dlg.FileName;

            currentStandard = (CityModelItem)Enum.Parse(typeof(CityModelItem), barEditItem1.EditValue.ToString());
            int ImgCnt = 0; // 总待处理图片数量

            // 将索引目录按5000大小 分区后，存入缓冲队列
            List<ValueTuple<DirectoryInfo, List<List<PicAndMile>>>> streePic_CacheQueue = new();
            List<ValueTuple<DirectoryInfo, List<List<PicAndMile>>>> roadImage_CacheQueue = new();
            for (int proIndex = 0; proIndex < _Projects.Count; proIndex++)
            {
                ProjectInfo pro = _Projects[proIndex];

                string outPath;
                if (currentStandard == CityModelItem.江苏省单位一定制)
                {
                    outPath = targetBasePath + $"\\{pro._City + pro._District}";
                }
                else
                {
                    outPath = targetBasePath + "\\结果数据";
                }

                string outPathResult = outPath + "\\" + pro.ConvertProName;
                string sourcePath = pro.ConvertPath.FullName;
                FileHelpter.CopyFileAndDir(sourcePath, outPathResult); // 第二次调用时，路径sourcePath不更新，仍会使用旧项目的文件。如果删除则找不到文件
                DirectoryInfo info = new DirectoryInfo(outPathResult);

                DirectoryInfo tempPath;
                //景观图像存储路径
                DirectoryInfo streePic = null;
                DirectoryInfo roadImage = null;

                void DeleteEmptyFolder(string path)
                {
                    foreach(var d in Directory.GetDirectories(path))
                    {
                        try { Directory.Delete(d); }
                        catch (Exception ex) {
                        }
                    }
                    
                }
                // 处理不同的格式要求
                switch (currentStandard)
                {
                    case CityModelItem.交通部2024规范:
                    case CityModelItem.安徽省单位一定制:
                        if (chebtn.Checked)
                        {
                            tempPath = info.GetDirectories("ViewImages").First();
                            streePic = tempPath.GetDirectories("*" + pro.DateDay + "*", SearchOption.AllDirectories).First();
                            roadImage = info.GetDirectories("Images").First().GetDirectories("*" + pro.DateDay + "*", SearchOption.AllDirectories).First();
                        }
                        else
                        {
                            //删除影像文件夹
                            string temp = outPathResult + "\\Images";
                            string temp1 = outPathResult + "\\ViewImages";
                            Directory.Delete(temp, true);
                            Directory.Delete(temp1, true);
                        }
                        break;
                    case CityModelItem.河南省单位一农村路定制:
                        if (chebtn.Checked)
                        {
                            tempPath = info.GetDirectories("景观图像").First();
                            streePic = tempPath.GetDirectories("*_*", SearchOption.AllDirectories).First();
                            roadImage = info.GetDirectories("Images").First().GetDirectories("*_*", SearchOption.AllDirectories).First();
                        }
                        else
                        {
                            //删除影像文件夹
                            string temp = outPathResult + "\\Images";
                            string temp1 = outPathResult + "\\景观图像";
                            Directory.Delete(temp, true);
                            Directory.Delete(temp1, true);
                        }
                        break;
                    case CityModelItem.湖南省单位一定制:
                        if (chebtn.Checked)
                        {
                            tempPath = info.GetDirectories("前方图像").First();
                            streePic = tempPath.GetDirectories().First().GetDirectories().First();
                            roadImage = info.GetDirectories("Images").First().GetDirectories("0", SearchOption.AllDirectories).First();
                        }
                        else
                        {
                            //删除影像文件夹
                            string temp = outPathResult + "\\Images";
                            string temp1 = outPathResult + "\\前方图像";
                            Directory.Delete(temp, true);
                            Directory.Delete(temp1, true);
                        }
                        break;
                    case CityModelItem.重庆市单位一定制:
                        if (chebtn.Checked)
                        {
                            tempPath = info.GetDirectories("ViewImages").First();
                            streePic = tempPath.GetDirectories("*" + pro.DateDay + "*", SearchOption.AllDirectories).First();
                            roadImage = info.GetDirectories("Images").First().GetDirectories("*" + pro.DateDay + "*", SearchOption.AllDirectories).First();
                        }
                        else
                        {
                            //删除影像文件夹
                            string temp = outPathResult + "\\Images";
                            string temp1 = outPathResult + "\\ViewImages";
                            Directory.Delete(temp, true);
                            Directory.Delete(temp1, true);
                        }
                        break;
                    case CityModelItem.甘肃省单位一定制:
                        if (chebtn.Checked)
                        {
                            tempPath = info.GetDirectories("ViewImages").First();
                            streePic = tempPath.GetDirectories("*" + pro.DateDay + "*", SearchOption.AllDirectories).First();
                            roadImage = info.GetDirectories("Images").First().GetDirectories("*" + pro.DateDay + "*", SearchOption.AllDirectories).First();
                        }
                        else
                        {
                            //删除影像文件夹
                            string temp = outPathResult + "\\Images";
                            string temp1 = outPathResult + "\\ViewImages";
                            Directory.Delete(temp, true);
                            Directory.Delete(temp1, true);
                        }
                        break;
                    case CityModelItem.河北省单位一定制:
                    case CityModelItem.河北省单位二定制:
                        if (chebtn.Checked)
                        {
                            tempPath = info.GetDirectories("ViewImages").First();
                            streePic = tempPath.GetDirectories("*" + pro.DateDay + "*", SearchOption.AllDirectories).First();
                            roadImage = info.GetDirectories("Images").First().GetDirectories("*" + pro.DateDay + "*", SearchOption.AllDirectories).First();
                        }
                        else
                        {
                            //删除影像文件夹
                            string temp = outPathResult + "\\Images";
                            string temp1 = outPathResult + "\\ViewImages";
                            Directory.Delete(temp, true);
                            Directory.Delete(temp1, true);
                        }
                        break;
                    case CityModelItem.江苏省单位一定制:
                        if (chebtn.Checked)
                        {
                            _Suf = ".jpeg";
                            
                            tempPath = info.GetDirectories("ViewImage").First();
                            streePic = tempPath.GetDirectories("*" + pro.DateDay + "*", SearchOption.AllDirectories).First();
                            roadImage = info.GetDirectories("Images").First().GetDirectories("*" + pro.DateDay + "*", SearchOption.AllDirectories).First();
                        }
                        else
                        {
                            //删除影像文件夹
                            string temp = outPathResult + "\\Images";
                            string temp1 = outPathResult + "\\ViewImage";
                            Directory.Delete(temp, true);
                            Directory.Delete(temp1, true);
                        }
                        break;
                        
                    default:
                        break;
                }
                DeleteEmptyFolder(info.FullName);
                if (chebtn.Checked)
                {
                    if (!string.IsNullOrWhiteSpace(pro.RoadPicPath))
                    {
                        var (cnt,roadImageIdx_5000_split) = ConvertPci(pro, roadImage, true);
                        ImgCnt += cnt;
                        roadImage_CacheQueue.Add( (roadImage, roadImageIdx_5000_split) );
                    }
                    else
                    {
                        Console.WriteLine((proIndex, roadImage));
                    }
                    if (!string.IsNullOrWhiteSpace(pro.StreetPicPath))
                    {
                        var (cnt, streePicIdx_5000_split) = ConvertPci(pro, streePic, false);
                        ImgCnt += cnt;
                        streePic_CacheQueue.Add( (streePic, streePicIdx_5000_split) );
                    }
                    else
                    {
                        Console.WriteLine((proIndex,streePic));
                    }
                }

                //pro.SetConvertSign(true);
                //progressBar1.Value = 100 * (proIndex + 1);

                //处理一下fileindex.txt的空行

                FileInfo[] indexFiles = info.GetFiles("fileindex.txt", SearchOption.AllDirectories);
                foreach (FileInfo file in indexFiles)
                {
                    var strings = File.ReadAllLines(file.FullName).ToList();
                    for (int i = strings.Count - 1; i >= 0; i--)
                    {
                        string temp = strings[i];
                        if (string.IsNullOrEmpty(temp))
                        {
                            strings.RemoveAt(i);
                        }
                    }
                    SaveFile(file.FullName, strings.ToArray(), false);
                }
                DirectoryInfo[] hasDirs = info.GetDirectories("Text", SearchOption.AllDirectories);
                ConvertToCity(info, pro);
                var allFiles = info.GetFiles("*", SearchOption.AllDirectories);
                foreach (var file in allFiles)
                {
                    handelCsvFiles.Add(file.FullName);
                }

            }

            // 进度条 最大值设置为图片总数
            this.progressBar1.Value = 0;
            this.progressBar1.Minimum = 0;
            this.progressBar1.Maximum = ImgCnt;
            this.Process = new Progress<int>(Value => progressBar1.Value += Value);

            //输出图片
            for (int proIndex = 0; proIndex < _Projects.Count; proIndex++)
            { 
                if (proIndex < streePic_CacheQueue.Count)
                {
                    var (streePic, streePic_spList) = streePic_CacheQueue[proIndex];
                    await MovePicutre(streePic, streePic_spList, currentStandard);
                }
                if (proIndex < roadImage_CacheQueue.Count)
                {
                    var (roadImage, roadImage_spList) = roadImage_CacheQueue[proIndex];
                    await MovePicutre(roadImage, roadImage_spList, currentStandard);
                }

            }

            //所有文件合并
            MessageBox.Show("所有项目处理完毕请检查!");
        }



        private static List<string> handelCsvFiles = new List<string>(); //已经处理过的文件
        /// <summary>
        /// 转换结果文件符合各地标准
        /// </summary>
        /// <param name="info"></param>
        private void ConvertToCity(DirectoryInfo info, ProjectInfo pro)
        {
            //c111-IRI-0.1-20220711
            //名称不包含时刻
            FileInfo[] iriFiles = info.GetFiles("*IRI*.csv", SearchOption.AllDirectories);
            FileInfo[] lbiFiles = info.GetFiles("*LBI*.csv", SearchOption.AllDirectories);
            //只有等级公路有车辙
            FileInfo[] rdFiles = info.GetFiles("*RD*.csv", SearchOption.AllDirectories);
            FileInfo[] mpdFiles = info.GetFiles("*MPD*.csv", SearchOption.AllDirectories);

            FileInfo[] drFiles = info.GetFiles("*DR*", SearchOption.AllDirectories);

            //c111-IRI-0.1-2022071-131313
            //时刻由-间隔
            FileInfo[] lpFiles = info.GetFiles("*LP*.csv", SearchOption.AllDirectories);
            FileInfo[] pbFiles = info.GetFiles("*PB*.csv", SearchOption.AllDirectories);
            FileInfo[] vbiFiles = info.GetFiles("*VBI*.csv", SearchOption.AllDirectories);
            FileInfo[] acceleFiles = info.GetFiles("*加速度*.csv", SearchOption.AllDirectories);
            //C6666-DR-0.6-10.6-20220716-标准沥青.CSV       等级公路病害
            //C8888-DR-0.8-10.8-20220718-指南沥青.CSV       低等级农村路病害
            FileInfo[] lqFiles = info.GetFiles("*沥*", SearchOption.AllDirectories);
            FileInfo[] snFiles = info.GetFiles("*水*", SearchOption.AllDirectories);
            FileInfo[] ssFiles = info.GetFiles("*砂*", SearchOption.AllDirectories);



        }
        //河北规范, 移动目标文件
        private void changeDirNameMoveFile()
        {

        }
        public static void DeleteFolders(string path)
        {
            try
            {
                // 检查路径是否存在
                if (!Directory.Exists(path))
                {
                    Console.WriteLine($"路径 {path} 不存在。");
                    return;
                }

                // 获取该路径下所有文件夹
                string[] folders = Directory.GetDirectories(path);

                foreach (string folder in folders)
                {

                    // 递归删除子文件夹
                    DeleteFolders(folder);

                    // 删除当前文件夹
                    Directory.Delete(folder, true);
                    Console.WriteLine($"已删除文件夹 {folder}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"删除文件夹时发生错误：{ex.Message}");
            }
        }
        public void WriteDataToExcel(string modelPath, DataTable dt, string outPath, int startIndex = -1)
        {
            // 读取模板文件
            using (FileStream fs = new FileStream(modelPath, FileMode.Open, FileAccess.Read))
            {
                XSSFWorkbook workbook = new XSSFWorkbook(fs);
                ISheet sheet = workbook.GetSheetAt(0); // 获取第一个工作表
                int rowIndex = startIndex;
                // 找到第一个没有数据的行
                if (startIndex == -1)
                {
                    rowIndex = FindFirstEmptyRow(sheet);
                }


                // 写入数据
                foreach (DataRow row in dt.Rows)
                {
                    IRow dataRow = sheet.CreateRow(rowIndex);

                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        object value = row[i];
                        dataRow.CreateCell(i).SetCellValue(value.ToString());
                    }

                    rowIndex++;
                }

                // 保存文件
                using (FileStream output = new FileStream(outPath, FileMode.Create))
                {
                    workbook.Write(output);
                }
            }
        }

        private int FindFirstEmptyRow(ISheet sheet)
        {
            int rowIndex = 0;
            IRow row = sheet.GetRow(rowIndex);

            while (row != null && !HasEmptyCells(row))
            {
                rowIndex++;
                row = sheet.GetRow(rowIndex);
            }

            return rowIndex;
        }

        private bool HasEmptyCells(IRow row)
        {

            ICell cell = row.GetCell(0, MissingCellPolicy.RETURN_NULL_AND_BLANK);

            if (cell == null || cell.CellType == CellType.Blank)
            {
                return true;
            }
            else
            {
                return false;
            }


        }
        private string findModelExcelPath(string basePath, string fillter)
        {
            string path = "";
            DirectoryInfo directory = new DirectoryInfo(basePath);



            foreach (FileInfo file in directory.GetFiles("*.xlsx"))
            {
                if (file.Name.Contains(fillter))
                {
                    path = file.FullName;
                    break;
                }
            }
            if (string.IsNullOrEmpty(path))
            {
                throw new Exception("找不到模板文件" + fillter);
            }
            return path;
        }
        public void InsertColumnWithValue(string value, DataTable dataTable, int index = 0)
        {
            DataColumn newColumn = new DataColumn();
            newColumn.DefaultValue = value;

            dataTable.Columns.Add(newColumn);
            dataTable.Columns[dataTable.Columns.Count - 1].SetOrdinal(index);
        }
        public void SwapColumns(DataTable dataTable, int column1Index, int column2Index)
        {
            if (column1Index < 0 || column1Index >= dataTable.Columns.Count
                || column2Index < 0 || column2Index >= dataTable.Columns.Count)
            {
                throw new ArgumentException("Invalid column index.");
            }

            DataColumn column1 = dataTable.Columns[column1Index];
            DataColumn column2 = dataTable.Columns[column2Index];

            int column1Ordinal = column1.Ordinal;
            column1.SetOrdinal(column2.Ordinal);
            column2.SetOrdinal(column1Ordinal);
        }
        public void InsertColumnWithValue(DataColumn newColumn, DataTable dataTable, int index = 0)
        {
            dataTable.Columns.Add(newColumn);
            dataTable.Columns[dataTable.Columns.Count - 1].SetOrdinal(index);
        }
        private static void ChangeFileName3_HN(ProjectInfo pro, FileInfo[] lqFiles, string dName)
        {
            foreach (var file in lqFiles)
            {
                if (handelCsvFiles.Contains(file.FullName))
                {
                    continue;
                }
                string fullName = file.FullName;

                string fatherPath = Path.GetDirectoryName(fullName);


                string FileName = Path.GetFileNameWithoutExtension(file.FullName);
                string[] spS = FileName.Split('-');
                if (spS.Length > 0)
                {
                    string cityCode = spS[0];

                    string startMile = spS[2];
                    string endMile = spS[3];
                    var year = pro._DataDate;
                    string newName = string.Join("-", cityCode, "DR", startMile, endMile, year, dName) + ".csv";
                    string nowFullPath = Path.Combine(fatherPath, newName);

                    if (!File.Exists(nowFullPath))
                    {

                        Microsoft.VisualBasic.FileIO.FileSystem.RenameFile(fullName, newName);

                    }
                }


            }

        }

        private static void ChangeFileName2_HN(ProjectInfo pro, FileInfo[] lpFiles)
        {
            foreach (var file in lpFiles)
            {
                string fullName = file.FullName;
                if (handelCsvFiles.Contains(fullName))
                {
                    continue;
                }
                string fatherPath = Path.GetDirectoryName(fullName);

                string fileName = Path.GetFileNameWithoutExtension(file.FullName);
                int len = fileName.Length;

                string newName = fileName.Substring(0, len - 6) + "-" + pro._DataTime + ".csv";

                string nowFullPath = Path.Combine(fatherPath, newName);

                if (!File.Exists(nowFullPath))
                {
                    Microsoft.VisualBasic.FileIO.FileSystem.RenameFile(fullName, newName);

                }
            }
        }

        private static void ChangeFileName1_HN(FileInfo[] iriFiles)
        {
            foreach (var file in iriFiles)
            {

                string fullName = file.FullName;
                if (handelCsvFiles.Contains(fullName))
                {
                    continue;
                }
                string fatherPath = Path.GetDirectoryName(fullName);

                string fileName = Path.GetFileNameWithoutExtension(file.FullName);
                int len = fileName.Length;
                string newName = fileName.Substring(0, len - 6) + ".csv";
                string nowFullPath = Path.Combine(fatherPath, newName);


                if (!File.Exists(nowFullPath))
                {
                    Microsoft.VisualBasic.FileIO.FileSystem.RenameFile(fullName, newName);

                }

            }
        }

        private List<string> stringToListString(string str)
        {
            List<string> ttemp = new List<string>();
            return ttemp = str.Split(',').ToList();

        }
        /// <summary>
        /// 移动 alldir下某个文件夹到某个文件夹下
        /// </summary>
        /// <param name="allDir"></param>
        /// <param name="sourceDir"></param>
        /// <param name="disDir"></param>
        private void MoveDirToDir(DirectoryInfo info, string sourceDir, string disDir)
        {
            DirectoryInfo iriDir = info.GetDirectories(sourceDir).FirstOrDefault();
            DirectoryInfo RIFileDir = info.GetDirectories(disDir).FirstOrDefault();
            DirectoryInfo directoryInfo = Directory.CreateDirectory(Path.Combine(RIFileDir.FullName, sourceDir));
            FileHelpter.CopyFileAndDir(iriDir.FullName, directoryInfo.FullName);
            FileInfo[] fileInfos = iriDir.GetFiles();
            Directory.Delete(iriDir.FullName, true);
        }
        private void ChangeConvert_henan(FileInfo[] iriFiles, string head, List<string> headTxt)
        {
            foreach (var item in iriFiles)
            {
                string fullName = item.FullName;
                if (handelCsvFiles.Contains(fullName))
                {
                    continue;
                }
                DataTable dt = CsvHelper.ReadDataFromCsv(item.FullName);

                DataTable dtOut = ChangeMile_henan(dt, headTxt);

                if (!string.IsNullOrEmpty(head))
                {
                    InsertFirstName(dtOut, head);
                }
                CsvHelper.WriteDataToCsv(dtOut, item.FullName);

            }
        }

        /// <summary>
        /// 断面高程 桩号为0.1m间隔  4位小数
        /// </summary>
        /// <param name="iriFiles"></param>
        /// <param name="head"></param>
        private void ChangeConvert_henan_iriH(FileInfo[] iriFiles, string head, List<string> headTxts)
        {
            foreach (var item in iriFiles)
            {
                string fullName = item.FullName;
                if (handelCsvFiles.Contains(fullName))
                {
                    continue;
                }
                DataTable dt = CsvHelper.ReadDataFromCsv(item.FullName);

                DataTable dtOut = ChangeMile_henan_iriH(dt, headTxts);
                if (!string.IsNullOrEmpty(head))
                {
                    InsertFirstName(dtOut, head);
                }
                CsvHelper.WriteDataToCsv(dtOut, item.FullName);

            }
        }
        /// <summary>
        ///当DataTable中有值时，是不允许修改列的DataType
        /// 修改数据表DataTable某一列的数据类型和记录值
        /// </summary>
        /// <param name="argDataTable">数据表DataTable</param>
        /// <returns>数据表DataTable</returns>
        private DataTable UpdateDataTable(DataTable argDataTable, int colNum)
        {
            DataTable dtResult = new DataTable();
            //克隆表结构
            dtResult = argDataTable.Clone();
            //修改数据列类型
            dtResult.Columns[colNum].DataType = typeof(string);
            //foreach (DataColumn col in dtResult.Columns)
            //{

            //    col.DataType = typeof(int);

            //}
            return dtResult;
        }

        private DataTable ChangeMile_henan(DataTable dt, List<string> heads)
        {
            DataTable dtOut = UpdateDataTable(dt, 0);
            //桩号为K0+000格式

            int colNum = dtOut.Columns.Count;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow dr = dtOut.NewRow();
                var nowRow = dt.Rows[i];
                for (int t = 0; t < colNum; t++)
                {
                    var cell = nowRow[t];
                    if (t == 0)
                    {
                        string txt = cell.ToString();
                        double temp;
                        bool result = double.TryParse(txt, out temp);
                        if (result)
                        {
                            cell = (temp * 1000).ToString("K0+000");
                        }
                    }
                    if (heads != null && heads.Count == colNum)
                    {
                        if (i == 0)
                        {
                            cell = heads[t];
                        }
                    }
                    dr[t] = cell;
                }
                dtOut.Rows.Add(dr);
            }
            //foreach (DataRow drOne in dtOut.Rows)
            //{
            //    var cell = drOne[0];

            //    string txt = drOne[0].ToString();
            //    double temp;
            //    bool result = double.TryParse(txt, out temp);
            //    if (result)
            //    {
            //        cell = "ccc";
            //        //cell = (temp * 1000).ToString("K0+000");
            //    }
            //}
            return dtOut;
        }
        /// <summary>
        /// 修改表头
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="heads"></param>
        /// <returns></returns>
        private DataTable ChangeHead_gansu(DataTable dt, List<string> heads)
        {
            DataTable dtOut = UpdateDataTable(dt, 0);


            int colNum = dtOut.Columns.Count;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow dr = dtOut.NewRow();
                var nowRow = dt.Rows[i];
                for (int t = 0; t < colNum; t++)
                {
                    var cell = nowRow[t];
                    //if (t == 0)
                    //{
                    //    string txt = cell.ToString();
                    //    double temp;
                    //    bool result = double.TryParse(txt, out temp);
                    //    if (result)
                    //    {
                    //        cell = (temp * 1000).ToString("K0+000");
                    //    }
                    //}
                    if (heads != null && heads.Count == colNum)
                    {
                        if (i == 0)
                        {
                            cell = heads[t];
                        }
                    }
                    dr[t] = cell;
                }
                dtOut.Rows.Add(dr);
            }
            //foreach (DataRow drOne in dtOut.Rows)
            //{
            //    var cell = drOne[0];

            //    string txt = drOne[0].ToString();
            //    double temp;
            //    bool result = double.TryParse(txt, out temp);
            //    if (result)
            //    {
            //        cell = "ccc";
            //        //cell = (temp * 1000).ToString("K0+000");
            //    }
            //}
            return dtOut;
        }
        private DataTable ChangeHead_gansu_iri(DataTable dt, List<string> heads)
        {
            DataTable dtOut = UpdateDataTable(dt, 0);


            int colNum = dtOut.Columns.Count;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow dr = dtOut.NewRow();
                var nowRow = dt.Rows[i];
                for (int t = 0; t < colNum; t++)
                {
                    var cell = nowRow[t];
                    if (t == 1) //iri数据列
                    {
                        string txt = cell.ToString();
                        double temp;
                        bool result = double.TryParse(txt, out temp);
                        if (result)
                        {
                            cell = temp.ToString("f2");
                        }
                    }
                    if (heads != null && heads.Count == colNum)
                    {
                        if (i == 0)
                        {
                            cell = heads[t];
                        }
                    }
                    dr[t] = cell;
                }
                dtOut.Rows.Add(dr);
            }
            //foreach (DataRow drOne in dtOut.Rows)
            //{
            //    var cell = drOne[0];

            //    string txt = drOne[0].ToString();
            //    double temp;
            //    bool result = double.TryParse(txt, out temp);
            //    if (result)
            //    {
            //        cell = "ccc";
            //        //cell = (temp * 1000).ToString("K0+000");
            //    }
            //}
            return dtOut;
        }
        /// <summary>
        /// 修改表头文字
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        private DataTable ChangeHead_henan(DataTable dt, List<string> heads)
        {
            DataTable dtOut = UpdateDataTable(dt, 0);


            DataRow dt0 = dt.Rows[0];

            int colNum = dtOut.Columns.Count;

            for (int i = 0; i < colNum; i++)
            {
                var cell = dt0[i];
                cell = heads[i];
            }

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow dr = dtOut.NewRow();
                var nowRow = dt.Rows[i];
                for (int t = 0; t < colNum; t++)
                {
                    var cell = nowRow[t];
                    if (t == 0)
                    {
                        string txt = cell.ToString();
                        double temp;
                        bool result = double.TryParse(txt, out temp);
                        if (result)
                        {
                            cell = (temp * 1000).ToString("K0+000");
                        }
                    }

                    dr[t] = cell;
                    if (i == 0)
                    {
                        string txt = cell.ToString();
                        txt = txt.Replace("\"", "");
                        cell = txt;

                    }
                }
                dtOut.Rows.Add(dr);
            }

            return dtOut;
        }
        private DataTable ChangeMile_henan_iriH(DataTable dt, List<string> heads)
        {
            DataTable dtOut = UpdateDataTable(dt, 0);
            //桩号为K0+000格式

            int colNum = dtOut.Columns.Count;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow dr = dtOut.NewRow();
                var nowRow = dt.Rows[i];
                for (int t = 0; t < colNum; t++)
                {
                    var cell = nowRow[t];
                    if (t == 0)
                    {
                        string txt = cell.ToString();
                        double temp;
                        bool result = double.TryParse(txt, out temp);
                        if (result)
                        {
                            cell = (temp * 10000).ToString("K0+0000");
                        }
                    }
                    if (heads != null && heads.Count == colNum)
                    {
                        if (i == 0)
                        {
                            cell = heads[t];
                        }
                    }
                    dr[t] = cell;
                }
                dtOut.Rows.Add(dr);
            }
            //foreach (DataRow drOne in dtOut.Rows)
            //{
            //    var cell = drOne[0];

            //    string txt = drOne[0].ToString();
            //    double temp;
            //    bool result = double.TryParse(txt, out temp);
            //    if (result)
            //    {
            //        cell = "ccc";
            //        //cell = (temp * 1000).ToString("K0+000");
            //    }
            //}
            return dtOut;
        }

        private void InsertFirstName(DataTable dt, string name)
        {
            DataRow dr = dt.NewRow();
            dr[0] = name;
            dt.Rows.InsertAt(dr, 0);
        }
        private void ChangeConvert_gansu(FileInfo[] iriFiles, string head, List<string> headTxt)
        {
            foreach (var item in iriFiles)
            {
                string fullName = item.FullName;
                if (handelCsvFiles.Contains(fullName))
                {
                    continue;
                }
                DataTable dt = CsvHelper.ReadDataFromCsv(item.FullName);

                DataTable dtOut = ChangeHead_gansu(dt, headTxt);


                CsvHelper.WriteDataToCsv(dtOut, item.FullName);

            }
        }
        /// <summary>
        /// 总是报错  iri精度不足2位  再这里处理一下
        /// </summary>
        /// <param name="iriFiles"></param>
        /// <param name="head"></param>
        /// <param name="headTxt"></param>
        private void ChangeConvert_gansu_iri(FileInfo[] iriFiles, string head, List<string> headTxt)
        {
            foreach (var item in iriFiles)
            {
                string fullName = item.FullName;
                if (handelCsvFiles.Contains(fullName))
                {
                    continue;
                }
                DataTable dt = CsvHelper.ReadDataFromCsv(item.FullName);

                DataTable dtOut = ChangeHead_gansu_iri(dt, headTxt);


                CsvHelper.WriteDataToCsv(dtOut, item.FullName);

            }
        }
        /// <summary>
        /// 转换图片工程
        /// </summary>
        /// <param name="pro"></param>
        /// <param name="image"></param>
        /// <param name="isRoad">true 路面破损 false 景观</param>
        private ValueTuple<int, List<List<PicAndMile>>> ConvertPci(ProjectInfo pro, DirectoryInfo image, bool isRoad)
        {

            string indexText = image.FullName + "\\fileindex.txt";

            //if (File.Exists(indexText))
            //{
            //    //存在则将生成的文件加入到后面去
            //    // FileStream fs = new FileStream(indexText,FileMode.Open);
            //    List<PicAndMile> _picAndMiles = pro.GetPicAndMiles(isRoad,currentStandard);
            //    string proName = pro.ConvertProName;
            //    string timeYear = pro.DateDay;
            //    WriteIndexTxt(indexText,ref _picAndMiles, proName, timeYear, true);

            //    List<List<PicAndMile>> spList = SplitPicAndMileList_5000(_picAndMiles);

            //    //  this.progressBar1.Maximum = indexPro*1000+50; //文本文件写完了

            //    await MovePicutre(image, spList, indexPro,currentStandard);
            //}
            //else
            //{
            //    //FileStream indexFile = File.Create(indexText,encoding:encoding);
            //    //indexFile.Close();
            //    List<PicAndMile> _picAndMiles = pro.GetPicAndMiles(isRoad,currentStandard);
            //    string proName = pro.ConvertProName;
            //    string timeYear = pro.DateDay;

            //    WriteIndexTxt(indexText,ref  _picAndMiles, proName, timeYear, false);
            //    List<List<PicAndMile>> spList = SplitPicAndMileList_5000(_picAndMiles);
            //    await MovePicutre(image, spList, indexPro,currentStandard);
            //}

            List<PicAndMile> _picAndMiles = pro.GetPicAndMiles(isRoad, currentStandard);
            int total_cnt = _picAndMiles.Count;
            string proName = pro.ConvertProName;
            string timeYear = pro.DateDay;

            WriteIndexTxt(pro, indexText, ref _picAndMiles, proName, timeYear, false);
            List<List<PicAndMile>> spList = SplitPicAndMileList_5000(_picAndMiles);
            return (total_cnt, spList);

            //await MovePicutre(image, spList, currentStandard);


        }

        private async Task ConvertPciHuNan(ProjectInfo pro, DirectoryInfo image, bool isRoad, int indexPro)
        {

            string indexText = image.FullName + "\\0\\" + "fileindex.txt";
            if (!Directory.Exists(image.FullName + "\\0"))
            {
                Directory.CreateDirectory(image.FullName + "\\0");
            }

            if (File.Exists(indexText))
            {

                List<PicAndMile> _picAndMiles = pro.GetPicAndMilesHuNan(isRoad);
                string proName = pro.ConvertProName;
                string timeYear = pro.DateDay;
                WriteIndexTxtHuNan(indexText, _picAndMiles, proName, timeYear, true);
                List<List<PicAndMile>> spList = SplitPicAndMileList_5000HuNan(_picAndMiles);


                await MovePicutreHuNan(image, spList, indexPro);
            }
            else
            {
                File.Create(indexText);
                List<PicAndMile> _picAndMiles = pro.GetPicAndMilesHuNan(isRoad);
                string proName = pro.ConvertProName;
                string timeYear = pro.DateDay;
                WriteIndexTxtHuNan(indexText, _picAndMiles, proName, timeYear, false);
                List<List<PicAndMile>> spList = SplitPicAndMileList_5000HuNan(_picAndMiles);


                await MovePicutreHuNan(image, spList, indexPro);
            }


        }

        /// <summary>
        /// 复制图片 
        /// 多线程
        /// </summary>
        /// <param name="image"></param>
        /// <param name="spList"></param>
        private async Task MovePicutre(DirectoryInfo image, List<List<PicAndMile>> spList, CityModelItem stanard)
        {
            for (int z = 0; z < spList.Count; z++)
            {

                List<PicAndMile> source = spList[z];
                int t = z + 1;
                string dirName = t.ToString("00");
                switch (stanard)
                {
                    case CityModelItem.交通部2024规范:
                        break;
                    case CityModelItem.河南省单位一农村路定制:
                        break;
                    case CityModelItem.湖南省单位一定制:
                        t = z;
                        dirName = t.ToString("0");
                        break;
                    case CityModelItem.重庆市单位一定制:
                        break;
                    case CityModelItem.甘肃省单位一定制:
                        break;
                    case CityModelItem.河北省单位一定制:
                        break;
                    case CityModelItem.江苏省单位一定制:
                        break;
                    default:
                        break;
                }

                await Task.Run(() =>
                
                    DoWork(ref source, image, dirName, this.Process)
                   
                );
            }
        }


        private void DoWork(ref List<PicAndMile> source, DirectoryInfo image, string dirName, IProgress<int> progress)
        {
            for (int i = 0; i < source.Count; i++)
            {
                //创建存储图片文件夹 
                string basePicPath = image.FullName + "\\" + dirName;
                Directory.CreateDirectory(basePicPath);

                string picSoucePath = source[i].PicPath;
                string targetPath = basePicPath + "\\" + source[i].ResultPicName + _Suf;
                if (File.Exists(picSoucePath))
                {
                    File.Copy(picSoucePath, targetPath, true);
                    progress.Report(1);
                }
            }

        }

        private async Task MovePicutreHuNan(DirectoryInfo image, List<List<PicAndMile>> spList, int indexPro)
        {
            for (int z = 0; z < spList.Count; z++)
            {

                List<PicAndMile> source = spList[z];
                // int t = z + 1;
                int t = z;
                await Task.Run(() =>
                {

                    for (int i = 0; i < source.Count; i++)
                    {

                        string dirName = t.ToString();
                        //创建存储图片文件夹 
                        string basePicPath = image.FullName + "\\0\\" + dirName;
                        Directory.CreateDirectory(basePicPath);
                        string picSoucePath = source[i].PicPath;
                        string targetPath = basePicPath + "\\" + source[i].ResultPicName + ".jpg";
                        if (File.Exists(picSoucePath))
                        {
                            File.Copy(picSoucePath, targetPath, true);
                        }


                    }
                }
                );
            }
        }
        public static int ProcessValue
        {
            set
            {

            }
        }
        /// <summary>
        /// 按照5000间隔对总图片结构进行切断
        /// </summary>
        /// <param name="_picAndMiles"></param>
        /// <returns></returns>
        private static List<List<PicAndMile>> SplitPicAndMileList_5000(List<PicAndMile> _picAndMiles)
        {
            int num = _picAndMiles.Count / 5000 + 1;
            List<List<PicAndMile>> spList = new List<List<PicAndMile>>();
            for (int i = 0; i < num; i++)
            {

                List<PicAndMile> picAndMiles = new List<PicAndMile>();
                for (int t = i * 5000; t < _picAndMiles.Count && t < (i + 1) * 5000; t++)
                {
                    picAndMiles.Add(_picAndMiles[t]);
                }
                spList.Add(picAndMiles);
            }

            return spList;
        }
        private static List<List<PicAndMile>> SplitPicAndMileList_5000HuNan(List<PicAndMile> _picAndMiles)
        {
            int num = _picAndMiles.Count / 5000 + 1;
            List<List<PicAndMile>> spList = new List<List<PicAndMile>>();
            for (int i = 0; i < num; i++)
            {

                List<PicAndMile> picAndMiles = new List<PicAndMile>();
                for (int t = i * 5000; t < _picAndMiles.Count && t < (i + 1) * 5000; t++)
                {
                    picAndMiles.Add(_picAndMiles[t]);
                }
                spList.Add(picAndMiles);
            }

            return spList;
        }
        /// <summary>
        /// 写 fileindex.txt
        /// </summary>
        /// <param name="fs"></param>
        /// <param name="_picAndMiles"></param>
        /// <param name="proName"></param>
        /// <param name="timeYear"></param>
        private void WriteIndexTxt(ProjectInfo pro, string path,ref List<PicAndMile> _picAndMiles, string proName, string timeYear, bool apped)
        {
            using (StreamWriter sw = new StreamWriter(path, apped))
            {
                string allMsg = "";
                for (int i = 0; i < _picAndMiles.Count; i++)
                {
                    string dirName = (i / 5000 + 1).ToString("00");
                    
                    string msg = "";
                    string picName = "";
                    PicAndMile updatedPicAndMile = _picAndMiles[i];
                    switch (currentStandard)
                    { 
                        case CityModelItem.河南省单位一农村路定制:
                            picName = Math.Round(_picAndMiles[i].Mile * 0.001, 3).ToString("0.000");
                            msg = proName + "->" + Math.Round(_picAndMiles[i].Mile * 0.001, 3).ToString("0.000")
                        + "->" + dirName + "->"+ picName + _Suf;
                            // 创建一个新的 PicAndMile 实例并更新 ResultPicName
                            updatedPicAndMile.updateResultPicName(picName);
                            _picAndMiles[i] = updatedPicAndMile; // 更新列表中的元素
                             break;
                        case CityModelItem.湖南省单位一定制:
                            picName = proName + "-" + _picAndMiles[i].Mile.ToString("000+000") + "000-" + _picAndMiles[i].Mile.ToString("000+000") + "000";
                            dirName = (i / 5000 ).ToString("0");
                            msg = proName + "->" + _picAndMiles[i].Mile.ToString("000+000")
                        + "->" + dirName + "->" + picName + _Suf;
                            // 创建一个新的 PicAndMile 实例并更新 ResultPicName
                            updatedPicAndMile.updateResultPicName(picName);
                            _picAndMiles[i] = updatedPicAndMile; // 更新列表中的元素
                            break; 
                        case CityModelItem.甘肃省单位一定制:
                           // msg = $"{dirName}\\{proName.Substring(0,proName.Length-1)}-{Math.Round(_picAndMiles[i].Mile * 0.001, 3).ToString("0.000")}-{timeYear}.jpg";
                            msg = proName + "->" + _picAndMiles[i].Mile.ToString("0+000")
                      + "->" + dirName + "->" + timeYear + "_" + proName + "_"
                      + Math.Round(_picAndMiles[i].Mile * 0.001, 3).ToString("0.000") + _Suf;
                            break; 
                        case CityModelItem.江苏省单位一定制:
                            msg = $"{pro._City + pro._District}"  + "->" + proName + "->" + _picAndMiles[i].Mile.ToString("0+000")
                       + "->" + dirName + "->" + timeYear + "_" + proName + "_"
                       + Math.Round(_picAndMiles[i].Mile * 0.001, 3).ToString("0.000") + _Suf;
                            break; 
                        default:
                            msg = proName + "->" + _picAndMiles[i].Mile.ToString("000+000")
                      + "->" + dirName + "->" + timeYear + "_" + proName + "_"
                      + Math.Round(_picAndMiles[i].Mile * 0.001, 3).ToString("0.000") + _Suf;
                            break;
                    }
                    allMsg += msg + "\r\n";
                }
                sw.WriteLine(allMsg);
            }

        }
        private static void WriteIndexTxtHuNan(string fs, List<PicAndMile> _picAndMiles, string proName, string timeYear, bool append)
        {
            using (StreamWriter sw = new StreamWriter(fs, append))
            {
                string allMsg = "";
                for (int i = 0; i < _picAndMiles.Count; i++)
                {

                    // string dirName = (i / 5000 + 1).ToString();
                    string dirName = (i / 5000).ToString();
                    string mile = ConvertIntToFormattedString(_picAndMiles[i].Mile);
                    string picName = proName + "-" + mile + "-" + mile + ".jpg";
                    string msg = proName + "->" + mile
                        + "->" + dirName + "->" + picName;
                    allMsg += msg + "\r\n";
                }
                sw.WriteLine(allMsg);
            }
        }


        public static string ConvertIntToFormattedString(int value)
        {
            int thousands = value / 1000; // 获取千位以上的数字部分
            int hundreds = value % 1000; // 获取百位以下的数字部分

            string result = $"{thousands.ToString().PadLeft(3, '0')}+{hundreds.ToString().PadLeft(3, '0') + "000"}";
            return result;
        }

        List<FileInfo> DaqFiles = new List<FileInfo>();
        private Progress<int> Process;

        /// <summary>
        /// 自定义惯导平整度文件名称
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem3_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {

            this.treeList2.Nodes.Clear();
            DaqFiles.Clear();
            FolderBrowserDialog dlg = new FolderBrowserDialog();
            dlg.Description = "请选择需要转换的工程";
            dlg.SelectedPath = _config.UserPath;
            dlg.ShowDialog();
            if (dlg.SelectedPath != String.Empty)
            {
                if (dlg.SelectedPath.Substring(dlg.SelectedPath.Length - 1) == "\\")
                {
                    dlg.SelectedPath = dlg.SelectedPath.Remove(dlg.SelectedPath.Length - 1);
                }
                this.Chktxt_Path = dlg.SelectedPath;
                _config.UserPath = dlg.SelectedPath;
                ConfigManager.SaveConfig();
                DirectoryInfo directory = new DirectoryInfo(dlg.SelectedPath);
                DaqFiles = directory.GetFiles("*.daq", SearchOption.AllDirectories).ToList();
                DaqFiles.Sort((a, b) => StrCmpLogicalW(a.FullName, b.FullName));
                foreach (var pro in DaqFiles)
                {
                    TreeListNode node = this.treeList2.AppendNode(null, null);
                    // node.SetValue("name",pro._DataDir.Name) ;
                    node.SetValue("data", pro.Name);
                }
            }
        }



        private void BarEditItem1_EditValueChanged(object sender, EventArgs e)
        {
            _config.NowModel = barEditItem1.EditValue.ToString();
            ConfigManager.SaveConfig();
        }

        private void barButtonItem4_ItemClick(object sender, ItemClickEventArgs e)
        {
            foreach (var proj in _Projects)
            {
                var nowDir = proj._DataDir;
                DirectoryInfo[] ConvertDirs = nowDir.GetDirectories("ConverSource");
                foreach (var item in ConvertDirs)
                {
                    Directory.Delete(item.FullName, true);
                }

                FileInfo[] projectInfos = nowDir.GetFiles("ProjectInfo.txt");
                foreach (FileInfo file in projectInfos)
                {
                    var strings = File.ReadAllLines(file.FullName).ToList();
                    for (int i = strings.Count - 1; i >= 0; i--)
                    {
                        string temp = strings[i];
                        if (temp.Contains("县级行政区划代码") || temp.Contains("ConvertOk"))
                        {
                            strings.RemoveAt(i);
                        }
                    }
                    //ClearText(file.FullName);

                    SaveFile(file.FullName, strings.ToArray(), false);
                }

            }
            if (_Projects.Count > 0)
            {
                MessageBox.Show("清理完毕！");
            }
            else
            {
                MessageBox.Show("您还没有导入任何合格工程");
            }

        }

        private void ClearText(string textPath)
        {
            FileStream stream = File.Open(textPath, FileMode.OpenOrCreate, FileAccess.Write);
            stream.Seek(0, SeekOrigin.Begin);
            stream.SetLength(0);
            stream.Close();

        }
        private void SaveFile(string str, string text, bool saOrAp)
        {
            StreamWriter sw = new StreamWriter(str, saOrAp);
            sw.WriteLine(text);
            sw.Close();

        }
        private void SaveFile(string str, string[] text, bool saOrAp)
        {
            StreamWriter sw = new StreamWriter(str, saOrAp);
            foreach (string str2 in text)
            {
                sw.WriteLine(str2);
            }

            sw.Close();

        }

        private void barButtonItem6_ItemClick(object sender, ItemClickEventArgs e)
        {

        }

        private void barButtonItem7_ItemClick(object sender, ItemClickEventArgs e)
        {
            FolderBrowserDialog fd = new FolderBrowserDialog();
            fd.Description = "请选择河南2导出的结果文件夹";
            var result = fd.ShowDialog();
            if (result != DialogResult.OK)
            {
                return;
            }
            //获取上下行 
            DirectoryInfo dir = new DirectoryInfo(fd.SelectedPath);

            DirectoryInfo[] dis = dir.GetDirectories();
            for (int i = 0; i < dis.Length; i++)
            {
                string proName = "";
                proName = dis[i].Name;
                string basePath = dis[i].FullName;
                DirectoryInfo baseDir = new DirectoryInfo(basePath);
                try
                {


                    //获得上下行 
                    string dirction = "上行";

                    if (proName.EndsWith("B"))
                    {
                        dirction = "下行";
                    }

                    //获得路线编码 
                    string roadCode = proName.Substring(0, 10);


                    //获得检测日期
                    FileInfo[] files = dis[i].GetFiles("*.csv", SearchOption.AllDirectories);
                    string firstName = files.Where(t => t.Name.Contains("IRI")).First().Name;
                    string time = firstName.Split('-').Last().Split('-').First();
                    DateTime date;
                    try
                    {
                        date = DateTime.ParseExact(time, "yyyyMMdd", CultureInfo.InvariantCulture);

                    }
                    catch (Exception)
                    {
                        date = DateTime.ParseExact(time.Split('.').First(), "yyyyMMdd", CultureInfo.InvariantCulture);

                    }
                    time = date.ToString("yyyy/M/d");
                    #region 更新病害表
                    foreach (var item in files.Where(t => t.Name.Contains("DR")).ToList())
                    {
                        string fileName = item.Name;
                        string outName = basePath + "\\" + fileName;
                        DataTable dt = CsvHelper.ReadDataFromCsv(item.FullName);
                        if (string.IsNullOrEmpty(dt.Rows[0][1].ToString()))
                        {
                            dt.Rows[0].Delete();
                        }
                        // 在第0列插入一列
                        dt.Columns.Add("路线编码", typeof(string));
                        // 将新列移动到第0列
                        dt.Columns["路线编码"].SetOrdinal(0);

                        dt.Rows[0][0] = "路线编码";
                        for (int t = 1; t < dt.Rows.Count; t++)
                        {
                            dt.Rows[t][0] = roadCode;
                            string mile = dt.Rows[t][1].ToString();
                            dt.Rows[t][1] = (float.Parse(mile.Replace("K", "").Replace("+", "")) / 1000).ToString();

                        }
                        //    CsvHelper.WriteDataToCsv(dt, item.FullName);
                        CsvHelper.WriteDataToCsv(dt, outName);
                    }
                    #endregion
                    #region 更新空间定位表
                    foreach (var item in files.Where(t => t.Name.Contains("LBI")).ToList())
                    {
                        string fileName = item.Name;
                        string outName = basePath + "\\" + fileName;
                        DataTable dt = CsvHelper.ReadDataFromCsv(item.FullName);
                        dt.Columns.RemoveAt(3);
                        dt.Columns.RemoveAt(3);
                        // 在第0列插入一列
                        dt.Columns.Add("路线编码", typeof(string));
                        // 将新列移动到第0列
                        dt.Columns["路线编码"].SetOrdinal(0);

                        dt.Rows[0][0] = "路线编码";
                        // 在第0列插入一列
                        dt.Columns.Add("检测方向", typeof(string));
                        dt.Rows[0][dt.Columns.Count - 1] = "检测方向";
                        dt.Columns.Add("检测日期", typeof(string));
                        dt.Rows[0][dt.Columns.Count - 1] = "检测日期";

                        for (int t = 1; t < dt.Rows.Count; t++)
                        {
                            dt.Rows[t][0] = roadCode;

                            string mile = dt.Rows[t][1].ToString();
                            dt.Rows[t][1] = (float.Parse(mile.Replace("K", "").Replace("+", "")) / 1000).ToString();
                            dt.Rows[t][4] = dirction;
                            dt.Rows[t][5] = time;

                        }
                        //  CsvHelper.WriteDataToCsv(dt, item.FullName);
                        CsvHelper.WriteDataToCsv(dt, outName);
                    }
                    #endregion


                    #region 更新平整度表
                    foreach (var item in files.Where(t => t.Name.Contains("IRI")).ToList())
                    {
                        string fileName = item.Name;
                        string outName = basePath + "\\" + fileName;
                        DataTable dt = CsvHelper.ReadDataFromCsv(item.FullName);
                        if (string.IsNullOrEmpty(dt.Rows[0][1].ToString()))
                        {
                            dt.Rows[0].Delete();
                        }
                        // 在第0列插入一列
                        dt.Columns.Add("路线编码", typeof(string));
                        // 将新列移动到第0列
                        dt.Columns["路线编码"].SetOrdinal(0);

                        dt.Rows[0][0] = "路线编码";
                        // 在第0列插入一列
                        dt.Columns.Add("检测方向", typeof(string));
                        dt.Rows[0][dt.Columns.Count - 1] = "检测方向";
                        dt.Columns.Add("检测日期", typeof(string));
                        dt.Rows[0][dt.Columns.Count - 1] = "检测日期";

                        for (int t = 1; t < dt.Rows.Count; t++)
                        {
                            dt.Rows[t][0] = roadCode;

                            string mile = dt.Rows[t][1].ToString();
                            dt.Rows[t][1] = (float.Parse(mile.Replace("K", "").Replace("+", "")) / 1000).ToString();
                            dt.Rows[t][4] = dirction;
                            dt.Rows[t][5] = time;

                        }
                        //  CsvHelper.WriteDataToCsv(dt, item.FullName);
                        CsvHelper.WriteDataToCsv(dt, outName);
                    }

                    //删除除了图片的所有文件夹
                    DirectoryInfo[] dirs = baseDir.GetDirectories();

                    foreach (var item in dirs)
                    {
                        if (item.Name.Contains("景观图像") || item.Name.Contains("Images"))
                        {

                        }
                        else
                        {
                            Directory.Delete(item.FullName, true);
                        }
                    }
                    #endregion
                }
                catch (Exception ex)
                {

                    throw new Exception(ex.Message + "\n" + proName + "工程解析出错");
                }


            }
            MessageBox.Show("所有项目处理完毕请检查!");

        }


        private void barButtonItem8_ItemClick(object sender, ItemClickEventArgs e)
        {
            FolderBrowserDialog fd = new FolderBrowserDialog();
            fd.Description = "请选择河南2导出的结果文件夹";
            List<string> needDirPath = new List<string> { "LBI", "Images", "RIFile", "IRI", "景观图像", "识别结果" };
            var result = fd.ShowDialog();
            if (result != DialogResult.OK)
            {
                return;
            }
            //获取上下行 
            DirectoryInfo dir = new DirectoryInfo(fd.SelectedPath);

            DirectoryInfo[] dis = dir.GetDirectories();
            for (int i = 0; i < dis.Length; i++)
            {
                string proName = "";
                proName = dis[i].Name;
                string basePath = dis[i].FullName;
                DirectoryInfo baseDir = new DirectoryInfo(basePath);
                try
                {

                    //获得上下行 
                    string dirction = "上行";

                    if (proName.EndsWith("B"))
                    {
                        dirction = "下行";
                    }

                    //获得路线编码 
                    string roadCode = proName.Substring(0, 10);


                    //获得检测日期
                    FileInfo[] files = dis[i].GetFiles("*.csv", SearchOption.AllDirectories);



                    string firstName = Path.GetFileNameWithoutExtension(files.Where(t =>
                    {
                        if (t.Name.Contains("IRI"))
                        {
                            string[] s = Path.GetFileNameWithoutExtension(t.FullName).Split('-');
                            return s.Last().Length == 8;
                        }

                        return false;
                    }
                    ).First().FullName);
                    string time = firstName.Split('-').Last().Split('-').First();
                    DateTime date;
                    try
                    {
                        date = DateTime.ParseExact(time, "yyyyMMdd", CultureInfo.InvariantCulture);

                    }
                    catch (Exception)
                    {
                        date = DateTime.ParseExact(time.Split('.').First(), "yyyyMMdd", CultureInfo.InvariantCulture);

                    }
                    time = date.ToString("yyyy/M/d");
                    //路面文件夹
                    DirectoryInfo roadPicDir = baseDir.GetDirectories("Images").First();
                    DirectoryInfo streetPicDir = baseDir.GetDirectories("景观图像").First();

                    DirectoryInfo lbiDir = baseDir.GetDirectories("LBI").First();
                    DirectoryInfo iriDir = baseDir.GetDirectories("IRI").First();
                    DirectoryInfo disDir = baseDir.GetDirectories("识别结果").First();
                    FileInfo indexRoadFile = roadPicDir.GetFiles("fileindex.txt", SearchOption.AllDirectories).FirstOrDefault();
                    FileInfo indexStreetFile = streetPicDir.GetFiles("fileindex.txt", SearchOption.AllDirectories).FirstOrDefault();
                    FileInfo GPSFile = baseDir.GetFiles("GPS2Mile.txt").First();
                    //获得时分秒
                    string timeMille = roadPicDir.GetDirectories().First().GetDirectories().First().Name.Split('_').Last();
                    #region 处理图像
                    //处理路面图像
                    //修改 index文件
                    Dictionary<double, string> lbiAndGpsInfoDic = new Dictionary<double, string>();
                    List<string> gpsInfos = File.ReadAllLines(GPSFile.FullName).ToList();
                    foreach (var item in gpsInfos)
                    {
                        string[] strs = item.Split(' ');
                        try
                        {
                            if (!lbiAndGpsInfoDic.Keys.Contains(double.Parse(strs.Last()) / 1000))

                            {
                                lbiAndGpsInfoDic.Add(double.Parse(strs.Last()) / 1000, strs[1] + "," + strs[2]);

                            }

                        }
                        catch (Exception)
                        {
                            throw;

                        }

                    }
                    if (indexRoadFile != null)
                    {
                        List<string> indexFileTXT = File.ReadAllLines(indexRoadFile.FullName).ToList();


                        var pcis = roadPicDir.GetFiles("*.jpg", SearchOption.AllDirectories);
                        string oldGpsInfo = "";
                        foreach (var item in pcis)
                        {
                            string name = Path.GetFileNameWithoutExtension(item.FullName);
                            //桩号
                            double mile = double.Parse(name.Split('_').Last());
                            string gpsInfo = lbiAndGpsInfoDic.Last().Value;

                            if (dirction == "上行")
                            {
                                gpsInfo = lbiAndGpsInfoDic.First().Value;
                            }
                            oldGpsInfo = gpsInfo;

                            try
                            {
                                gpsInfo = lbiAndGpsInfoDic[mile];
                                oldGpsInfo = gpsInfo;
                            }
                            catch (Exception)
                            {

                                gpsInfo = oldGpsInfo;
                            }

                            string[] strs = gpsInfo.Split(',');
                            string mileStr = (mile * 1000).ToString("K000+000");

                            string newName = mileStr + "_" + strs[0] + "_" + strs[1] + ".jpg";

                            string newPath = Path.GetDirectoryName(item.FullName) + "\\" + newName;
                            File.Move(item.FullName, newPath);
                            for (int d = 0; d < indexFileTXT.Count; d++)
                            {
                                string line = indexFileTXT[d];
                                string[] temp2 = line.Split('>');
                                string temp22 = line.Split('>')[1].Replace("+", "");
                                double mileTxt = double.Parse(temp22.Substring(0, temp22.Length - 1));
                                if (mile * 1000 == mileTxt)
                                {
                                    string newLine = "";
                                    for (int ddd = 0; ddd < temp2.Length - 1; ddd++)
                                    {
                                        newLine += temp2[ddd] + ">";
                                    }
                                    newLine += newName;
                                    indexFileTXT[d] = newLine;
                                    break;
                                }
                            }
                        }
                        File.WriteAllLines(indexRoadFile.FullName, indexFileTXT);

                    }
                    if (indexStreetFile != null)
                    {
                        string oldGpsInfo = "";
                        List<string> indexFileTXT = File.ReadAllLines(indexStreetFile.FullName).ToList();
                        var pcis = streetPicDir.GetFiles("*.jpg", SearchOption.AllDirectories);
                        foreach (var item in pcis)
                        {
                            string name = Path.GetFileNameWithoutExtension(item.FullName);
                            //桩号
                            double mile = double.Parse(name.Split('_').Last());
                            string gpsInfo = lbiAndGpsInfoDic.Last().Value;
                            if (dirction == "上行")
                            {
                                gpsInfo = lbiAndGpsInfoDic.First().Value;
                            }
                            oldGpsInfo = gpsInfo;
                            try
                            {
                                gpsInfo = lbiAndGpsInfoDic[mile];
                                oldGpsInfo = gpsInfo;
                            }
                            catch (Exception)
                            {

                                gpsInfo = oldGpsInfo;
                            }

                            string[] strs = gpsInfo.Split(',');
                            string mileStr = (mile * 1000).ToString("K000+000");

                            string newName = mileStr + "_" + strs[0] + "_" + strs[1] + ".jpg";

                            string newPath = Path.GetDirectoryName(item.FullName) + "\\" + newName;
                            File.Move(item.FullName, newPath);
                            for (int d = 0; d < indexFileTXT.Count; d++)
                            {
                                string line = indexFileTXT[d];
                                string[] temp2 = line.Split('>');
                                string temp22 = line.Split('>')[1].Replace("+", "");
                                double mileTxt = double.Parse(temp22.Substring(0, temp22.Length - 1));
                                if (mileTxt == 1005)
                                {

                                }
                                double mile2 = mile * 1000;
                                if (Math.Abs(mileTxt - mile2) <= 0.0001)
                                {
                                    string newLine = "";
                                    for (int ddd = 0; ddd < temp2.Length - 1; ddd++)
                                    {
                                        newLine += temp2[ddd] + ">";
                                    }
                                    newLine += newName;
                                    indexFileTXT[d] = newLine;
                                    break;
                                }
                            }
                        }

                        File.WriteAllLines(indexStreetFile.FullName, indexFileTXT);
                    }
                    File.Delete(GPSFile.FullName);

                    #endregion

                    #region 更新病害表
                    foreach (var item in files.Where(t => { return Path.GetFileNameWithoutExtension(t.FullName).Split('-').Length == 6 && t.Name.Contains("DR"); }).ToList())
                    {
                        string fileName = Path.GetFileNameWithoutExtension(item.Name);
                        string[] silit = fileName.Split('-');
                        string tempOutName = "";
                        for (int d = 0; d < silit.Length; d++)
                        {
                            if (d == silit.Length - 2)
                            {


                            }
                            else if (d == silit.Length - 1)
                            {
                                tempOutName += silit[d];
                            }
                            else
                            {
                                tempOutName += silit[d] + "-";

                            }
                        }
                        string outName = disDir.FullName + "\\" + tempOutName + ".csv";
                        DataTable dt = CsvHelper.ReadDataFromCsv(item.FullName);
                        if (string.IsNullOrEmpty(dt.Rows[0][1].ToString()))
                        {
                            dt.Rows[0].Delete();
                        }
                        // 在第0列插入一列
                        dt.Columns.Add("路线编码", typeof(string));
                        // 将新列移动到第0列
                        dt.Columns["路线编码"].SetOrdinal(0);

                        dt.Rows[0][0] = "路线编码";
                        for (int t = 1; t < dt.Rows.Count; t++)
                        {
                            dt.Rows[t][0] = roadCode;
                            string mile = dt.Rows[t][1].ToString();
                            dt.Rows[t][1] = (float.Parse(mile.Replace("K", "").Replace("+", "")) / 1000).ToString();

                        }
                        //    CsvHelper.WriteDataToCsv(dt, item.FullName);
                        CsvHelper.WriteDataToCsv(dt, outName);
                        File.Delete(item.FullName);
                    }
                    #endregion
                    #region 更新空间定位表
                    //空间定位表 获得 桩号与gps信息

                    foreach (var item in files.Where(t => { return Path.GetFileNameWithoutExtension(t.FullName).Split('-').Last().Length == 8 && t.Name.Contains("LBI"); }).ToList())
                    {
                        string fileName = Path.GetFileNameWithoutExtension(item.FullName) + timeMille + ".csv";
                        string outName = lbiDir.FullName + "\\" + fileName;
                        DataTable dt = CsvHelper.ReadDataFromCsv(item.FullName);
                        dt.Columns.RemoveAt(3);
                        dt.Columns.RemoveAt(3);
                        // 在第0列插入一列
                        dt.Columns.Add("路线编码", typeof(string));
                        // 将新列移动到第0列
                        dt.Columns["路线编码"].SetOrdinal(0);

                        dt.Rows[0][0] = "路线编码";
                        // 在第0列插入一列
                        dt.Columns.Add("检测方向", typeof(string));
                        dt.Rows[0][dt.Columns.Count - 1] = "检测方向";
                        dt.Columns.Add("检测日期", typeof(string));
                        dt.Rows[0][dt.Columns.Count - 1] = "检测日期";

                        for (int t = 1; t < dt.Rows.Count; t++)
                        {
                            dt.Rows[t][0] = roadCode;

                            string mile = dt.Rows[t][1].ToString();
                            dt.Rows[t][1] = (float.Parse(mile.Replace("K", "").Replace("+", "")) / 1000).ToString();
                            dt.Rows[t][4] = dirction;
                            dt.Rows[t][5] = time;


                        }



                        //  CsvHelper.WriteDataToCsv(dt, item.FullName);
                        CsvHelper.WriteDataToCsv(dt, outName);
                        File.Delete(item.FullName);
                    }
                    #endregion


                    #region 更新平整度表
                    foreach (var item in files.Where(t =>
                    {
                        return Path.GetFileNameWithoutExtension(t.FullName).Split('-').Last().Length == 8 && t.Name.Contains("IRI");
                    }).ToList())
                    {
                        // string fileName = item.Name;
                        string fileName = Path.GetFileNameWithoutExtension(item.FullName) + timeMille + ".csv";
                        string outName = iriDir.FullName + "\\" + fileName;
                        DataTable dt = CsvHelper.ReadDataFromCsv(item.FullName);
                        if (string.IsNullOrEmpty(dt.Rows[0][1].ToString()))
                        {
                            dt.Rows[0].Delete();
                        }
                        // 在第0列插入一列
                        dt.Columns.Add("路线编码", typeof(string));
                        // 将新列移动到第0列
                        dt.Columns["路线编码"].SetOrdinal(0);

                        dt.Rows[0][0] = "路线编码";
                        // 在第0列插入一列
                        dt.Columns.Add("检测方向", typeof(string));
                        dt.Rows[0][dt.Columns.Count - 1] = "检测方向";
                        dt.Columns.Add("检测日期", typeof(string));
                        dt.Rows[0][dt.Columns.Count - 1] = "检测日期";

                        for (int t = 1; t < dt.Rows.Count; t++)
                        {
                            dt.Rows[t][0] = roadCode;

                            string mile = dt.Rows[t][1].ToString();
                            dt.Rows[t][1] = (float.Parse(mile.Replace("K", "").Replace("+", "")) / 1000).ToString();
                            dt.Rows[t][4] = dirction;
                            dt.Rows[t][5] = time;

                        }
                        //  CsvHelper.WriteDataToCsv(dt, item.FullName);
                        CsvHelper.WriteDataToCsv(dt, outName);
                        File.Delete(item.FullName);
                    }
                    foreach (var dirsName in baseDir.GetDirectories())
                    {
                        if (!needDirPath.Contains(dirsName.Name))
                        {
                            Directory.Delete(dirsName.FullName, true);
                        }

                    }

                    #endregion


                }
                catch (Exception ex)
                {

                    throw new Exception(ex.Message + "\n" + proName + "工程解析出错");
                }


            }
            MessageBox.Show("所有项目处理完毕请检查!");

        }




        private void barButtonItem10_ItemClick(object sender, ItemClickEventArgs e)
        {
            FolderBrowserDialog fd = new FolderBrowserDialog();
            fd.Description = "请选择农村路规范导出的结果数据文件夹";
            var result = fd.ShowDialog();

            if (result != DialogResult.OK)
            {
                return;
            }


            //获取上下行 
            DirectoryInfo dir = new DirectoryInfo(fd.SelectedPath);
            DirectoryInfo[] diss = dir.GetDirectories();

            if (dir.Name != "结果数据")
            {
                MessageBox.Show("请选择农村路规范导出的结果数据文件夹");
                return;
            }
            foreach (var disStr in diss)
            {
                DirectoryInfo[] dis = disStr.GetDirectories();
                foreach (var dirPath in dis)
                {
                    var tempPath = dirPath.Name;
                    if (tempPath.Contains("Images"))
                    {
                        DirectoryInfo tempDir = dirPath.GetDirectories().FirstOrDefault();
                        if (tempDir.Name.Length == 14)
                        {
                            string dirName = tempDir.Name.Substring(0, tempDir.Name.Length - 2);

                            Microsoft.VisualBasic.FileIO.FileSystem.RenameDirectory(tempDir.FullName, dirName);

                        }

                    }
                    if (tempPath == "DR")
                    {
                        FileInfo[] files = dirPath.GetFiles();
                        foreach (var item in files)
                        {
                            string names = Path.GetFileNameWithoutExtension(item.FullName);
                            string[] temps = names.Split('-');
                            string newFile = "";
                            if (temps.Length == 6)
                            {
                                if (names.Contains("水泥"))
                                {
                                    newFile = string.Join("-", temps[0], double.Parse(temps[2]).ToString("0.000"), "《指南》水泥路面损坏自动化检测数据", temps[4]) + ".txt";
                                }
                                else if (names.Contains("沥青"))
                                {
                                    newFile = string.Join("-", temps[0], double.Parse(temps[2]).ToString("0.000"), "《指南》沥青路面损坏自动化检测数据", temps[4]) + ".txt";

                                }
                                else
                                {
                                    newFile = string.Join("-", temps[0], double.Parse(temps[2]).ToString("0.000"), "《指南》砂石路面损坏自动化检测数据", temps[4]) + ".txt";

                                }

                                newFile = Path.GetDirectoryName(item.FullName) + "\\" + newFile;

                                File.Move(item.FullName, newFile);
                            }
                        }
                    }
                }
            }


            MessageBox.Show("所有项目处理完毕请检查!");
        }

        private void barButtonItem11_ItemClick(object sender, ItemClickEventArgs e)
        {
            string helpfile = Application.StartupPath + "\\软件说明\\12 产品内业软件使用手册V1.1-20230707.docx";
            System.Diagnostics.Process.Start(helpfile);
        }

        private void barButtonItem12_ItemClick(object sender, ItemClickEventArgs e)
        {
            FolderBrowserDialog fd = new FolderBrowserDialog();
            fd.Description = "请选择农村路规范导出的结果数据文件夹";
            var result = fd.ShowDialog();

            if (result != DialogResult.OK)
            {
                return;
            }


            //获取上下行 
            DirectoryInfo dir = new DirectoryInfo(fd.SelectedPath);
            DirectoryInfo[] diss = dir.GetDirectories();

            if (dir.Name != "结果数据")
            {
                MessageBox.Show("请选择农村路规范导出的结果数据文件夹");
                return;
            }
            foreach (var disStr in diss)
            {
                DirectoryInfo[] dis = disStr.GetDirectories();
                foreach (var dirPath in dis)
                {
                    var tempPath = dirPath.Name;
                    if (tempPath.Contains("Images"))
                    {
                        DirectoryInfo tempDir = dirPath.GetDirectories().FirstOrDefault();
                        if (tempDir.Name.Length == 14)
                        {
                            string dirName = tempDir.Name.Substring(0, tempDir.Name.Length - 2);

                            Microsoft.VisualBasic.FileIO.FileSystem.RenameDirectory(tempDir.FullName, dirName);

                        }

                    }
                    if (tempPath == "DR")
                    {
                        FileInfo[] files = dirPath.GetFiles();
                        foreach (var item in files)
                        {
                            string names = Path.GetFileNameWithoutExtension(item.FullName);
                            string[] temps = names.Split('-');
                            string newFile = "";
                            if (temps.Length == 6)
                            {
                                if (names.Contains("水泥"))
                                {
                                    newFile = string.Join("-", temps[0], double.Parse(temps[2]).ToString("0.000"), "《指南》水泥路面损坏自动化检测数据", temps[4]) + ".txt";
                                }
                                else if (names.Contains("沥青"))
                                {
                                    newFile = string.Join("-", temps[0], double.Parse(temps[2]).ToString("0.000"), "《指南》沥青路面损坏自动化检测数据", temps[4]) + ".txt";

                                }
                                else
                                {
                                    newFile = string.Join("-", temps[0], double.Parse(temps[2]).ToString("0.000"), "《指南》砂石路面损坏自动化检测数据", temps[4]) + ".txt";

                                }

                                newFile = Path.GetDirectoryName(item.FullName) + "\\" + newFile;

                                File.Move(item.FullName, newFile);
                            }
                        }
                    }
                }
            }


            MessageBox.Show("所有项目处理完毕请检查!");
        }

        private void barButtonItem13_ItemClick(object sender, ItemClickEventArgs e)
        {

            FolderBrowserDialog fd = new FolderBrowserDialog();
            fd.Description = "请选择农村路规范导出的结果数据文件夹";
            var result = fd.ShowDialog();

            if (result != DialogResult.OK)
            {
                return;
            }
            //处理图片
            DialogResult dialogResult = MessageBox.Show("选择\"是\"进行图像名称修改,选否进行单张图片提取", "模式选择", MessageBoxButtons.YesNo);
            if (dialogResult == DialogResult.Yes)
            {
                //依据合肥规范进行 图片名称 和index.txt文件的修改
                DirectoryInfo dir = new DirectoryInfo(fd.SelectedPath);
                DirectoryInfo[] diss = dir.GetDirectories();

                for (int i = 0; i < diss.Length; i++)
                {
                    // DirectoryInfo dirInfo = diss[i];

                    foreach (var disStr in diss)
                    {
                        string roadCode = disStr.Name;
                        DirectoryInfo[] dis = disStr.GetDirectories();


                        foreach (var dirNow in dis)
                        {
                            List<string> lines = new List<string>();
                            var tempPath = dirNow.Name;
                            if (tempPath == "Images" || tempPath == "ViewImages")
                            {
                                string indexPath = Directory.GetFiles(dirNow.FullName, "fileindex.txt", SearchOption.AllDirectories).First();
                                //FileInfo indexFile = new FileInfo(indexPath);
                                string[] dirctoryFiles = Directory.GetFiles(dirNow.FullName, "*.jpg", SearchOption.AllDirectories);
                                progressBar1.Value = 0;
                                progressBar1.Maximum = dirctoryFiles.Length;
                                for (int d = 0; d < dirctoryFiles.Length; d++)
                                {
                                    progressBar1.Value = d + 1;
                                    string item = dirctoryFiles[d];
                                    FileInfo pciFile = new FileInfo(item);
                                    string name = Path.GetFileNameWithoutExtension(pciFile.FullName);
                                    int mile = int.Parse((double.Parse(name.Split('_').Last()) * 1000).ToString());
                                    string mileStr = Form1.ConvertIntToFormattedString(mile);
                                    string mileStr1 = mile.ToString("0+000");
                                    string picName = roadCode + "-" + mileStr + "-" + mileStr + ".jpg";
                                    string number = pciFile.Directory.Name;
                                    string lineStr = string.Format($"{roadCode}->{mileStr1}->{number}->{picName}");
                                    pciFile.MoveTo(pciFile.Directory.FullName + "\\" + picName);
                                    lines.Add(lineStr);
                                }
                                File.WriteAllLines(indexPath, lines);

                            }



                        }
                    }

                }
            }
            else if (dialogResult == DialogResult.No)
            {
                //景观和路面图像仅提取一张图片 

                FolderBrowserDialog fd1 = new FolderBrowserDialog();
                fd1.Description = "请选择输出地址";
                var result1 = fd1.ShowDialog();

                if (result1 != DialogResult.OK)
                {
                    return;
                }
                string resultPath = fd1.SelectedPath + "\\影像结果数据\\";


                DirectoryInfo dir = new DirectoryInfo(fd.SelectedPath);
                DirectoryInfo[] diss = dir.GetDirectories();

                for (int i = 0; i < diss.Length; i++)
                {
                    DirectoryInfo dirInfo = diss[i];

                    foreach (var disStr in diss)
                    {
                        DirectoryInfo[] dis = disStr.GetDirectories();


                        foreach (var dirNow in dis)
                        {
                            List<string> lines = new List<string>();
                            var tempPath = dirNow.Name;
                            if (tempPath == "Images" || tempPath == "ViewImages")
                            {
                                try
                                {
                                    string indexPath = Directory.GetFiles(dirNow.FullName, "fileindex.txt", SearchOption.AllDirectories).First();
                                    //FileInfo indexFile = new FileInfo(indexPath);
                                    string[] dirctoryFiles = Directory.GetFiles(dirNow.FullName, "*.jpg", SearchOption.AllDirectories);

                                    //复制index文件
                                    string targetIndexFilePath = resultPath + indexPath.Replace(fd.SelectedPath, "");
                                    FileInfo tempFile = new FileInfo(targetIndexFilePath);
                                    Directory.CreateDirectory(tempFile.DirectoryName);
                                    File.Copy(indexPath, targetIndexFilePath, true);

                                    //获取第一张图片地址
                                    if (dirctoryFiles.Length > 0)
                                    {
                                        FileInfo tempFile1 = new FileInfo(dirctoryFiles.FirstOrDefault());
                                        string targetPath = resultPath + tempFile1.DirectoryName.Replace(fd.SelectedPath, "");
                                        Directory.CreateDirectory(targetPath);
                                        File.Copy(tempFile1.FullName, targetPath + "\\" + tempFile1.Name);
                                    }
                                }
                                catch (Exception)
                                {

                                    MessageBox.Show("工程" + dirInfo.Name + "缺少必须图片或index文件请检查!");
                                }


                            }



                        }
                    }

                }
            }

            MessageBox.Show("处理完成!");

        }

        private void barButtonItem14_ItemClick(object sender, ItemClickEventArgs e)
        {
            FolderBrowserDialog fd = new FolderBrowserDialog();
            fd.Description = "请选择农村路规范导出的结果数据文件夹";

            var result = fd.ShowDialog();
            if (result != DialogResult.OK)
            {
                return;
            }
            //处理图片
            //依据合肥规范进行 图片名称 和index.txt文件的修改
            DirectoryInfo dir = new DirectoryInfo(fd.SelectedPath);
            DirectoryInfo[] diss = dir.GetDirectories();

            var result1 = MessageBox.Show("修改路面图像索引选择是,修改景观图像索引选择否", "提示", MessageBoxButtons.YesNo);

            ////修改文件夹名称 
            //foreach (var pro in diss)
            //{
            //    string proName = pro.Name;
            //    string newName = proName.Substring(0, 4) + proName.Last() + "-" + proName.Substring(4, 6);
            //    Microsoft.VisualBasic.FileIO.FileSystem.RenameDirectory(pro.FullName,newName);

            //}
            diss = dir.GetDirectories();
            //删除多余数据
            foreach (var item in diss)
            {
                DirectoryInfo[] dirChild = item.GetDirectories();
                foreach (var child in dirChild)
                {
                    string fix = "";
                    if (result1 == DialogResult.Yes)
                    {
                        fix = "Images";
                    }
                    else
                    {
                        fix = "ViewImages";
                    }
                    if (!child.Name.Equals(fix))
                    {
                        Directory.Delete(child.FullName, true);

                    }
                    else
                    {
                        //将里面的内容提取出去
                        DirectoryInfo dirCC = child.GetDirectories().First();
                        DirectoryInfo[] resultDir = dirCC.GetDirectories();
                        foreach (var itemDir in resultDir)
                        {
                            Directory.Move(itemDir.FullName, item.FullName + "/" + itemDir.Name);
                        }
                        FileInfo resultFile = dirCC.GetFiles().First();
                        File.Move(resultFile.FullName, item.FullName + "/" + resultFile.Name);
                        Directory.Delete(child.FullName, true);
                    }
                }
            }

            foreach (var pro in diss)
            {
                //更改index文件
                FileInfo indexFile = pro.GetFiles("fileindex.txt").First();
                List<string> indexTxts = File.ReadLines(indexFile.FullName).ToList();
                //根据各地标准模板_《2024-03-04检测图像格式的要求-wqq.docx》进行修改
                List<string> newIndexTxts = new List<string>();
                foreach (var line in indexTxts)
                {
                    string newLine = "";
                    string tempStr = line.Replace("-", string.Empty);
                    string mileMsg = tempStr.Split('>')[1];
                    newLine += mileMsg + ".jpg" + "->" + tempStr.Split('>').Last() + "->" + "\\" + tempStr.Split('>')[2];
                    newIndexTxts.Add(newLine);
                }
                File.WriteAllLines(indexFile.FullName, newIndexTxts);
            }
            MessageBox.Show("处理完成");
        }

        private void barButtonItem15_ItemClick(object sender, ItemClickEventArgs e)
        {
            FolderBrowserDialog fd = new FolderBrowserDialog();
            fd.Description = "请选择农村路规范导出的结果数据文件夹";
            var result = fd.ShowDialog();

            if (result != DialogResult.OK)
            {
                return;
            }

            //获取上下行 
            DirectoryInfo dir = new DirectoryInfo(fd.SelectedPath);
            DirectoryInfo[] diss = dir.GetDirectories();

            this.treeList2.Nodes.Clear();
            foreach (var pro in diss)
            {
                TreeListNode node = this.treeList2.AppendNode(null, null);
                // node.SetValue("name",pro._DataDir.Name) ;
                node.SetValue("data", pro.Name);
            }

            if (dir.Name != "结果数据")
            {
                MessageBox.Show("请选择农村路规范导出的结果数据文件夹");
                return;
            }
            foreach (var disStr in diss)
            {
                DirectoryInfo[] dis = disStr.GetDirectories();
                foreach (var dirPath in dis)
                {
                    var tempPath = dirPath.Name;
                    if (tempPath == "DR")
                    {
                        //去除文件名中 最后的中文字符 如 指南水泥
                        FileInfo[] files = dirPath.GetFiles();
                        foreach (var item in files)
                        {
                            string names = Path.GetFileNameWithoutExtension(item.FullName);
                            string newName = names.Substring(0, names.LastIndexOf('-')) + ".txt";
                            //第一行桩号改成起点桩号

                            string[] lines = File.ReadAllLines(item.FullName);
                            lines[0] = lines.First().Replace("桩号", "起点桩号");
                            File.WriteAllLines(item.FullName, lines);
                            Microsoft.VisualBasic.FileIO.FileSystem.RenameFile(item.FullName, newName);



                        }
                    }
                    if (tempPath == "LBI")
                    {
                        FileInfo[] files = dirPath.GetFiles();
                        foreach (var item in files)
                        {
                            string names = Path.GetFileNameWithoutExtension(item.FullName);

                            //第一行桩号改成起点桩号

                            string[] lines = File.ReadAllLines(item.FullName);
                            lines[0] = "起点桩号(km),经度,纬度";
                            for (int i = 1; i < lines.Length; i++)
                            {
                                lines[i] = lines[i].Substring(0, lines[i].LastIndexOf(','));
                            }

                            File.WriteAllLines(item.FullName, lines);
                        }
                    }

                    if (tempPath == "RIFile")
                    {
                        FileInfo[] files = dirPath.GetFiles();
                        foreach (var item in files)
                        {
                            string names = Path.GetFileNameWithoutExtension(item.FullName);

                            //第一行桩号改成起点桩号

                            string[] lines = File.ReadAllLines(item.FullName);
                            lines[0] = "起点桩号(km),左高程(mm),右高程(mm),速度(m/s)";

                            File.WriteAllLines(item.FullName, lines);
                        }
                    }
                }
            }

            string oldDirectoryName = fd.SelectedPath; // 旧文件夹路径
            string newDirectoryName = fd.SelectedPath.Substring(0, fd.SelectedPath.LastIndexOf("\\")) + "\\交通部二次修改"; // 新文件夹路径

            try
            {
                // 检查旧文件夹是否存在
                if (Directory.Exists(oldDirectoryName))
                {
                    // 修改文件夹名称
                    Directory.Move(oldDirectoryName, newDirectoryName);
                    Console.WriteLine("文件夹名称修改成功！");
                }
                else
                {
                    Console.WriteLine("指定的旧文件夹不存在！");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("修改文件夹名称时发生错误: " + ex.Message);
            }

            MessageBox.Show("所有项目处理完毕请检查!");
        }

        private void ribbonControl1_Click(object sender, EventArgs e)
        {

        }
    }
}
